﻿#include "funcexportcontroller.h"
#include <QFileInfo>
#include "utils/excelutil.h"

FuncExportController::FuncExportController()
{
    m_pHelper = DbMgr::instance()->getHelper();
    m_mapFunc.insert("/func/export/datagrid",  &FuncExportController::datagrid);
    m_mapFunc.insert("/func/export/xlsx",      &FuncExportController::exportXlsx);
    m_mapFunc.insert("/func/export/csv",       &FuncExportController::exportCsv);
    m_mapFunc.insert("/func/export/upload",    &FuncExportController::upload);

    //生成数据
    QStringList nameList;
    nameList << QStringLiteral("张三") << QStringLiteral("李四") << QStringLiteral("王五") << QStringLiteral("赵六");
    QStringList sexList;
    sexList << QStringLiteral("男") << QStringLiteral("女");
    QDateTime now = QDateTime::currentDateTime();
    for(int i=0; i<100; i++)
    {
        TestUser user;
        user.id = i+1;
        user.name = nameList[i%nameList.length()];
        qsrand((uint)QDateTime::currentMSecsSinceEpoch() + i);
        user.age = qrand()%30 + 10;
        user.balance = qrand() % 10000 + qrand() % 1000;
        QDateTime birth = now.addDays(0 - qrand() % 365);
        birth = birth.addYears(0 - user.age + now.date().year() - birth.date().year());
        user.birthday = birth.toMSecsSinceEpoch();        
        quint64 fullPhone = 15 * 10  + qrand() % 10;
        fullPhone = fullPhone *10000 *10000  + qrand() % 10000 *10000 + qrand() % 10000;
        user.phone = QString::number(fullPhone);
        user.createDate = birth;
        user.createName = "admin";
        user.sex = sexList[i%sexList.length()];
        userList.append(user);
    }
}

void FuncExportController::service(HttpRequest& request, HttpResponse& response)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString access_token = request.getParameter("access_token");
    QString username = JwtUtil::getUsername(access_token);
    if(username == NULL || username.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    SysUser visitUser;
    if(!m_pHelper->selectUserByName(visitUser, username))
    {
        ret.failedMsg(QStringLiteral("用户不存在，操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QByteArray path = request.getPath().toLower();
    if(m_mapFunc.contains(path))
    {
        pServFunc func = m_mapFunc.value(path);
        (this->*func)(request, response, visitUser);
    }
}

/*
http://localhost:9004/func/export/datagrid?page=1&limit=30&field=createDate&order=desc&access_token=?
page: 1
limit: 30
field: createDate
order: desc
name: 李四
access_token: ?
{"code":0,"count":42,"data":[{"age":30,"balance":32341.32,"birthday":629395200000,"createDate":1578275114000,"createName":"admin","id":"a5c3998cab3f35471cbafa20cbcaa0dd","name":"李四","phone":"13338800001","sex":"男","versions":0},{"age":26,"balance":1234.9,"birthday":754848000000,"createDate":1578275114000,"createName":"admin","id":"2501d4dd5a03dc753b250077ab28c8a7","name":"张三","phone":"13338800000","sex":"男","versions":0},{"age":27,"balance":32.0,"birthday":765302400000,"createDate":1578275114000,"createName":"admin","id":"334bf52abeade17f01422f45bd574185","name":"王红","phone":"13338800002","sex":"女","versions":0},{"age":0,"balance":0.0,"createDate":1578041563000,"createName":"admin","id":"cee5da95acb4104b05a56fcfcd923bb1","sex":"男","versions":0},{"age":26,"balance":1234.9,"birthday":754848000000,"createDate":1578041563000,"createName":"admin","id":"c072bc18c3f4b318d17885fa6c707401","name":"张三","phone":"13338800000","sex":"男","versions":0},{"age":30,"balance":32341.32,"birthday":629395200000,"createDate":1578041563000,"createName":"admin","id":"7d57596325acda748c01fd4134532460","name":"李四","phone":"13338800001","sex":"男","versions":0},{"age":27,"balance":32.0,"birthday":765302400000,"createDate":1578041563000,"createName":"admin","id":"4afa43c938600e139281df78844701bb","name":"王红","phone":"13338800002","sex":"女","versions":0},{"age":27,"balance":32.0,"birthday":765302400000,"createDate":1578041530000,"createName":"admin","id":"f6975d83eda9373049c97d8e82020bc3","name":"王红","phone":"13338800002","sex":"女","versions":0},{"age":30,"balance":32341.32,"birthday":629395200000,"createDate":1578041530000,"createName":"admin","id":"9bbfaaf608361025ca6c571ccfc82b2b","name":"李四","phone":"13338800001","sex":"男","versions":0},{"age":0,"balance":0.0,"createDate":1578041530000,"createName":"admin","id":"90595af5c8279a67cd378f8770a98d06","sex":"男","versions":0},{"age":26,"balance":1234.9,"birthday":754848000000,"createDate":1578041530000,"createName":"admin","id":"7e73a1da9c586a0cc2907ff21c4e71cb","name":"张三","phone":"13338800000","sex":"男","versions":0},{"age":30,"balance":32341.32,"birthday":629395200000,"createDate":1578041485000,"createName":"admin","id":"25dab48f40778a466fafcdd31f8b1534","name":"李四","phone":"13338800001","sex":"男","versions":0},{"age":27,"balance":32.0,"birthday":765302400000,"createDate":1578041485000,"createName":"admin","id":"056aa96e685f42dcd45e554365172552","name":"王红","phone":"13338800002","sex":"女","versions":0},{"age":26,"balance":1234.9,"birthday":754848000000,"createDate":1578041485000,"createName":"admin","id":"b3fc868d3e24f04769a7ec553a373b37","name":"张三","phone":"13338800000","sex":"男","versions":0},{"age":0,"balance":0.0,"createDate":1578041485000,"createName":"admin","id":"51dae6f4f232f967a8779117bb5aef56","sex":"男","versions":0},{"age":27,"balance":32.0,"birthday":765302400000,"createDate":1578041476000,"createName":"admin","id":"3f44fde020ecc0be0f64b4ec542e5c65","name":"王红","phone":"13338800002","sex":"女","versions":0},{"age":26,"balance":1234.9,"birthday":754848000000,"createDate":1578041476000,"createName":"admin","id":"5b1a83066ef31a8e73287245aacac2b9","name":"张三","phone":"13338800000","sex":"男","versions":0},{"age":30,"balance":32341.32,"birthday":629395200000,"createDate":1578041476000,"createName":"admin","id":"0daccd1837e81558d459636cc1fbb4fd","name":"李四","phone":"13338800001","sex":"男","versions":0},{"age":0,"balance":0.0,"createDate":1578041476000,"createName":"admin","id":"31b5c0390d832ea36d9c8d456d235da7","sex":"男","versions":0},{"age":26,"balance":1234.9,"birthday":754848000000,"createDate":1576576923000,"createName":"admin","id":"5365e7f244ae3e1d4f38ee0a491988ee","name":"张三","phone":"13338800000","sex":"男","versions":0},{"age":30,"balance":32341.32,"birthday":629395200000,"createDate":1576576923000,"createName":"admin","id":"dcdc99fb28aead25ea8b6177a114feed","name":"李四","phone":"13338800001","sex":"男","versions":0},{"age":0,"balance":0.0,"createDate":1576576923000,"createName":"admin","id":"c09f32fd98e3587ef45c9ebfc619f641","sex":"男","versions":0},{"age":27,"balance":32.0,"birthday":765302400000,"createDate":1576576923000,"createName":"admin","id":"b59c109c8823360f8e27c29e16ed543e","name":"王红","phone":"13338800002","sex":"女","versions":0},{"age":27,"balance":32.0,"birthday":765302400000,"createDate":1576574603000,"createName":"admin","id":"168f50533b41eecc0c6b273df2bf0502","name":"王红","phone":"13338800002","sex":"女","versions":0},{"age":26,"balance":1234.9,"birthday":754848000000,"createDate":1576574603000,"createName":"admin","id":"514fa3f4b6b45d41d3406d2524deaacf","name":"张三","phone":"13338800000","sex":"男","versions":0},{"age":30,"balance":32341.32,"birthday":629395200000,"createDate":1576574603000,"createName":"admin","id":"3c37b8eba7e0b85df0c95c47c416c72d","name":"李四","phone":"13338800001","sex":"男","versions":0},{"age":27,"balance":32.0,"birthday":765302400000,"createDate":1576574306000,"createName":"admin","id":"5880bc6371d1b4f0db5e2d7cdb974d0d","name":"王红","phone":"13338800002","sex":"女","versions":0},{"age":30,"balance":32341.32,"birthday":629395200000,"createDate":1576574306000,"createName":"admin","id":"a409417fb82edb9f5a37af5c1534d06d","name":"李四","phone":"13338800001","sex":"男","versions":0},{"age":26,"balance":1234.9,"birthday":754848000000,"createDate":1576574306000,"createName":"admin","id":"7ba5441b2fc97c08ce307357888c789c","name":"张三","phone":"13338800000","sex":"男","versions":0},{"age":27,"balance":32.0,"createDate":1576574209000,"createName":"admin","id":"7d9f232affbe35e369c085c6d1d18299","name":"王红","phone":"13338800002","sex":"女","versions":0}],"msg":""}
*/
bool userLessThan(const TestUser &s1, const TestUser &s2){return s1.createDate < s2.createDate;}
void FuncExportController::datagrid(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    int page = 1;
    int limit = 30;
    QString field = "createDate";
    QString order = "desc";
    QString name = "";

    if(request.getParameterMap().contains("page"))  page  = request.getParameter("page").toInt();
    if(request.getParameterMap().contains("limit")) limit = request.getParameter("limit").toInt();
    if(request.getParameterMap().contains("field")) field = request.getParameter("field");
    if(request.getParameterMap().contains("order")) order = request.getParameter("order");
    if(request.getParameterMap().contains("name"))  name  = request.getParameter("name");

    QList<TestUser> tmpList;
    for(int i=0; i<userList.length(); i++)
    {
        if(name.isEmpty())
        {
            tmpList.append(userList[i]);
        }
        else if(userList[i].name.contains(name))
        {
            tmpList.append(userList[i]);
        }
    }


    int count = tmpList.length();
    qSort(tmpList.begin(), tmpList.end(), userLessThan);
    QJsonArray dataArray;
    for(int i=(page-1)*limit; i<page*limit; i++)
    {
        if(i >= count)
            break;
        QJsonObject obj ;
        obj.insert("id", tmpList[i].id);
        obj.insert("versions", tmpList[i].versions);
        obj.insert("createName", tmpList[i].createName);
        obj.insert("createDate", tmpList[i].createDate.toMSecsSinceEpoch());
        obj.insert("name", tmpList[i].name);
        obj.insert("age", tmpList[i].age);
        obj.insert("balance", tmpList[i].balance);
        obj.insert("birthday", tmpList[i].birthday);
        obj.insert("phone", tmpList[i].phone);
        obj.insert("sex", tmpList[i].sex);

        dataArray.append(obj);
    }
    ResultJson ret(0, true, QStringLiteral(""));
    ret.setProp("count", count);
    ret.setData(dataArray);
    ResponseUtil::replyJson(response, ret);

}

//http://localhost:9004/func/export/xlsx?name=&access_token=？
void FuncExportController::exportXlsx(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    QString name = request.getParameter("name");
    qSort(userList.begin(), userList.end(), userLessThan);

    //基于QtXlsx生成EXCEL文件，下载

    QList<QStringList> dataList;
    QStringList head;
    head << QStringLiteral("姓名")   << QStringLiteral("性别") << QStringLiteral("年龄")
         << QStringLiteral("手机号") << QStringLiteral("生日") << QStringLiteral("余额/元");

    dataList.append(head);
    for(int i=0; i<userList.length(); i++)
    {
        if(!name.isEmpty() && !userList[i].name.contains(name))
        {
            continue;
        }
        QStringList data;
        data << userList[i].name
             << userList[i].sex
             << QString::number(userList[i].age)
             << userList[i].phone
             << userList[i].createDate.toString("yyyy-MM-dd hh:mm:ss")
             << QString::number(userList[i].balance);

        dataList.append(data);
    }

    QString UUID = QUuid::createUuid().toString().remove("{").remove("}");
    QString fileName = GlobalFunc::instance()->configDir + "/etc/" +  UUID + ".xlsx";

    ResultJson ret(0, true, QStringLiteral("操作成功"));
    if(!ExcelUtil::exportExcelFile(fileName, dataList))
    {
        ret.failedMsg(QStringLiteral("文件生成失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    ResponseUtil::replyFile(response, fileName);

}

//http://localhost:9004/func/export/csv?name=&access_token=?
void FuncExportController::exportCsv(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    QString name = request.getParameter("name");
    qSort(userList.begin(), userList.end(), userLessThan);

    QList<QStringList> dataList;
    QStringList head;
    head << QStringLiteral("姓名")   << QStringLiteral("性别") << QStringLiteral("年龄")
         << QStringLiteral("手机号") << QStringLiteral("生日") << QStringLiteral("余额/元");

    dataList.append(head);
    for(int i=0; i<userList.length(); i++)
    {
        if(!name.isEmpty() && !userList[i].name.contains(name))
        {
            continue;
        }
        QStringList data;
        data << userList[i].name
             << userList[i].sex
             << QString::number(userList[i].age)
             << userList[i].phone
             << userList[i].createDate.toString("yyyy-MM-dd hh:mm:ss")
             << QString::number(userList[i].balance);

        dataList.append(data);
    }

    QString UUID = QUuid::createUuid().toString().remove("{").remove("}");
    QString fileName = GlobalFunc::instance()->configDir + "/etc/" +  UUID + ".csv";

    ResultJson ret(0, true, QStringLiteral("操作成功"));
    if(!ExcelUtil::exportCsvFile(fileName, dataList))
    {
        ret.failedMsg(QStringLiteral("文件生成失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    ResponseUtil::replyFile(response, fileName);
}

//http://localhost:9004/func/export/upload?access_token=？
//{"code":0,"success":false,"msg":"导入文件失败","data":null}
void FuncExportController::upload(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    QStringList nameList;
    QMultiMap<QByteArray,QByteArray> paramMap = request.getParameterMap();
    foreach(QByteArray fieldName, paramMap.keys())
    {
        if(fieldName == QString("access_token"))
        {
            continue;
        }
        QString fileName = QString(paramMap.value(fieldName));  //上传文件名
        QTemporaryFile* file = request.getUploadedFile(fieldName);  //上传文件临时存储

        //本地硬盘保存，暂不考虑大文件
        QFileInfo info(fileName);
        QString UUID = QUuid::createUuid().toString().remove("{").remove("}");
        QString localFileName = GlobalFunc::instance()->configDir + "/etc/" +  UUID + "." + info.suffix();
        QFile localFile(localFileName);
        localFile.open(QIODevice::WriteOnly);
        localFile.write(file->readAll());
        localFile.close();

        nameList << localFileName;
    }

    ret.setData(nameList.join(","));
    ResponseUtil::replyJson(response, ret);
}
